package com.fss.user.action;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;

import com.fss.user.service.UserService;
import com.fss.util.AbstractSimpleAction;
import com.fss.util.EnCode;
import com.fssDataModels.TbUser;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;

public class UserAction extends AbstractSimpleAction{
	private TbUser user;
	private UserService userService;
	private List<TbUser> userlist;
	private List<TbUser> contactList;
	

	private String num_confirm;
	private ByteArrayInputStream inputStream;
	private String DateStr;
	private String oldPSW;
	private String newPSW;
	private String newPSWAgain;
	private String userIds;//checked users for delete
	private String contactId;


	@Override
	public String initAdd() throws Exception {
		ActionContext.getContext().getSession().remove("rand");
		return SUCCESS;
	}

	@Override
	public String doAdd() throws Exception {
		if(!ActionContext.getContext().getSession().get("rand").equals(this.num_confirm.trim())){
			this.msg ="認証数字が違います！";
			return INPUT;
		}
		if(this.userService.isExist(this.user.getUserId())){
			this.msg ="希望するユーザーIDが存在している！";
			this.user.setUserId("");
			
			return INPUT;
		}else{
			EnCode encode=new EnCode();
			this.user.setPwd(encode.md5Encode(this.user.getPwd()));
			this.userService.addUser(user);
			return SUCCESS;
		}
	}

	public String showUserInfo(){
		Map session = ActionContext.getContext().getSession();
		this.user = (TbUser) session.get("user_login");
		this.contactList=this.userService.getContects(this.user);
		return SUCCESS;
	}
	
	@Override
	public String initEdit() throws Exception {
		Map session = ActionContext.getContext().getSession();
		this.user = (TbUser) session.get("user_login");
		if(this.user==null){
			return ERROR;
		}
		return SUCCESS;
	}

	@Override
	public String doEdit() throws Exception {
		Map session = ActionContext.getContext().getSession();
		TbUser user_temp = (TbUser) session.get("user_login");
		if(user_temp==null){
			return ERROR;
		}
		
		
		user_temp.setDisplayName(this.user.getDisplayName().trim());
		user_temp.setBirthday(this.user.getBirthday().trim());
		user_temp.setSex(this.user.getSex().trim());//why not int?
		user_temp.setEmail(this.user.getEmail().trim());
		//user_temp.setRealName(this.user.getRealName().trim());
		user_temp.setNationality(this.user.getNationality().trim());
		user_temp.setWorkingPlace(this.user.getWorkingPlace().trim());
		//user_temp.setAddress(this.user.getAddress().trim());//nullPointer exception

		this.userService.editUser(user_temp);
		
		return SUCCESS;
	}
	
	@SuppressWarnings("deprecation")
	public String initUserManage() throws ParseException{
		String admins[]={"fss_admin1","fss_admin2","fss_admin3"};
		Map session = ActionContext.getContext().getSession();
		TbUser user_temp = (TbUser) session.get("user_login");
    	if(user_temp == null){
    		return ERROR;
    	}
    	int i=0;
    	while(i<admins.length ){
    		
            if (user_temp.getUserId().equals(admins[i])){
            	
            	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d");
        		if(this.DateStr==null||this.DateStr.trim()==""){
        			this.DateStr = sdf.format(new Date());
        			this.userlist=this.userService.getUsersByDate(new Date());
        		}else{
        			Date toDate = sdf.parse(this.DateStr.trim());
        			toDate.setHours(23);
        			toDate.setMinutes(59);
        			toDate.setSeconds(59);
        			
        			this.userlist=this.userService.getUsersByDate(toDate);
        		}
        		
        		return SUCCESS;
            }
            ++i;
    	}
    	
    	return ERROR;
		
	}
	
	
	public String doChangePwd(){
		Map session = ActionContext.getContext().getSession();
		TbUser user_temp = (TbUser) session.get("user_login");
		
		EnCode enCode=new EnCode();
		
		if(!enCode.md5Encode(this.oldPSW).equalsIgnoreCase(user_temp.getPwd().trim())){
			this.msg ="パスワードが違います！";
			this.oldPSW="";
			this.newPSW="";
			this.newPSWAgain="";
			this.user=user_temp;
			
			session.put(ERROR, this.msg);
			
			return INPUT;
		}else if(!this.newPSW.equalsIgnoreCase(this.newPSWAgain.trim())){
			this.msg="二回入力したパスワードが違います！";
			
			this.oldPSW="";
			this.newPSW="";
			this.newPSWAgain="";
			this.user=user_temp;
			
			session.put(ERROR, this.msg);
			return INPUT;
		}else{
			user_temp.setPwd(enCode.md5Encode(this.newPSW.trim()));
			this.userService.editUser(user_temp);
			session.put("user_login", user_temp);
			
			this.msg="パスワードが変更しました！";
			session.put(ERROR, this.msg);
			
			return SUCCESS;
		}
		
	}

	@Override
	public String doDelete() throws Exception {
		//Json
		try {
			this.userService.deleteUser(this.user.getUserId());
			setJsonMessage(SUCCESS, "User has been deleted.");
		} catch (Throwable ex) {
			setJsonMessage(ERROR, ex.getMessage());
		}
		return SUCCESS;
	}
	
	public String deleteAll() throws Exception{
		String [] userId;
		userId=this.userIds.split(",");
		try{
			this.userService.deleteAllUser(userId);
			this.userIds="";
			this.msg="削除しました！";
		}catch(Throwable ex){
			this.msg="削除失敗！もう一回試したください。";
		}
		return SUCCESS;
	}
	
	public String doDeleteContact() throws Exception {
		//Json
		try {
			this.userService.deleteContact(this.contactId);
			setJsonMessage(SUCCESS, "User has been deleted.");
		} catch (Throwable ex) {
			setJsonMessage(ERROR, ex.getMessage());
		}
		return SUCCESS;
	}
	
	public String isUseable() throws Exception{
		try{
			if(this.userService.isExist(this.user.getUserId())){
				setJsonMessage("false", "このユーザＩＤもう存在しています。");
				System.out.println("false");
			}else{
				setJsonMessage("true", "このユーザＩＤが使えます");
				System.out.println("true");
			}
		}catch (Throwable ex){
			setJsonMessage(ERROR, ex.getMessage());
			System.out.println("error");
		}
		return SUCCESS;
	}
	public String doSearchUsers() throws ParseException{
		    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date toDate = sdf.parse(this.DateStr.trim());

			this.userlist=this.userService.getUsersByDate(toDate);
			
			return SUCCESS;			
	}
		
	public String doRand() throws Exception{
			getRandomNum();
			return SUCCESS;
	}
		/*
		 * 给定范围获得随机颜色
		 */
	private Color getRandColor(int fc,int bc){
	        Random random = new Random();
	        if(fc>255) fc=255;
	        if(bc>255) bc=255;
	        int r=fc+random.nextInt(bc-fc);
	        int g=fc+random.nextInt(bc-fc);
	        int b=fc+random.nextInt(bc-fc);
	        return new Color(r,g,b);
	 }
		
	private void getRandomNum()throws Exception{
			int width=85, height=20;
			BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//			 获取图形上下文
			Graphics g = image.getGraphics();
//			生成随机类
			Random random = new Random();
//			 设定背景色
			g.setColor(getRandColor(200,250));
			g.fillRect(0, 0, width, height);
//			设定字体
			g.setFont(new Font("Times New Roman",Font.PLAIN,18));
//			 随机产生155条干扰线，使图象中的认证码不易被其它程序探测到
			g.setColor(getRandColor(160,200));
			for (int i=0;i<155;i++)
			{
			 int x = random.nextInt(width);
			 int y = random.nextInt(height);
			        int xl = random.nextInt(12);
			        int yl = random.nextInt(12);
			 g.drawLine(x,y,x+xl,y+yl);
			}
//			 取随机产生的认证码(6位数字)
			String sRand="";
			for (int i=0;i<6;i++){
			    String rand=String.valueOf(random.nextInt(10));
			    sRand+=rand;
			    // 将认证码显示到图象中
			    g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));
//			调用函数出来的颜色相同，可能是因为种子太接近，所以只能直接生成
			    g.drawString(rand,13*i+6,16);
			}
//			 将认证码存入SESSION
			
			ActionContext.getContext().getSession().put("rand",sRand);
//			 图象生效
			g.dispose();
			ByteArrayOutputStream output = new ByteArrayOutputStream();
	        ImageOutputStream imageOut = ImageIO.createImageOutputStream(output);
	        ImageIO.write(image, "JPEG", imageOut);
	        imageOut.close();
	        ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());
	        this.setInputStream(input);
	}
		
	public void setInputStream(ByteArrayInputStream inputStream) {
			this.inputStream = inputStream;
		}
	
	public ByteArrayInputStream getInputStream() {
			return inputStream;
		}

	public String doCancel(){
		return SUCCESS;
	}
	
	public TbUser getUser() {
		return user;
	}

	public void setUser(TbUser user) {
		this.user = user;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public String getOldPSW() {
		return oldPSW;
	}

	public void setOldPSW(String oldPSW) {
		this.oldPSW = oldPSW;
	}

	public String getNewPSW() {
		return newPSW;
	}

	public void setNewPSW(String newPSW) {
		this.newPSW = newPSW;
	}

	public String getNewPSWAgain() {
		return newPSWAgain;
	}

	public void setNewPSWAgain(String newPSWAgain) {
		this.newPSWAgain = newPSWAgain;
	}

	public List<TbUser> getUserlist() {
		return userlist;
	}

	public void setUserlist(List<TbUser> userlist) {
		this.userlist = userlist;
	}

	public String getDateStr() {
		return DateStr;
	}

	public void setDateStr(String dateStr) {
		DateStr = dateStr;
	}

	

	public String getUserIds() {
		return userIds;
	}

	public void setUserIds(String userIds) {
		this.userIds = userIds;
	}

	public String getNum_confirm() {
		return num_confirm;
	}

	public void setNum_confirm(String num_confirm) {
		this.num_confirm = num_confirm;
	}

	public List<TbUser> getContactList() {
		return contactList;
	}

	public void setContactList(List<TbUser> contectList) {
		this.contactList = contectList;
	}

	public String getContactId() {
		return contactId;
	}

	public void setContactId(String contactId) {
		this.contactId = contactId;
	}

	
	
	
	
}